import axios from "axios";
import {config} from "../config/index.js";
import {ElMessage} from "element-plus";
import {useRouter} from "vue-router";

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

//创建一个新的实例
const service = axios.create({
    //以下为默认配置
    baseURL:'http://127.0.0.1:4523/m1/5787659-5472079-default',
    timeout:10000,
    headers:{
        'apifoxToken':'rVh3dSvcKeH944RSX63bz9JAJWrshf6b',
        'X-Request-With': 'XMLHttpRequest'
    }
})

//增加请求拦截器
service.interceptors.request.use(axiosConfig => {
    let token = localStorage.getItem(config.tokenName)
    console.log(token);
    if (token) {
        axiosConfig.headers['token'] = token;
    }
    let timeStr = (new Date()).getTime()
    if(axiosConfig.method === 'get'){
        if(axiosConfig.params){
            axiosConfig.params.timestamp = timeStr
        }else{
            axiosConfig.params = {
                timestamp : timeStr
            }
        }
    }
    return axiosConfig;
},(error) => {
    return Promise.reject(error)
})


// 响应拦截器
axios.interceptors.response.use((response)=>{
    if(response.data.code === 200){
        return Promise.resolve(response)
    }else if(response.data.code === 401){
        localStorage.removeItem(config.tokenName);
        ElMessage.error('登录状态已失效')
        if (response.currentRoute.path === '/login'){
            console.log('使用登录方法')
        }else{
            let router = useRouter();
            router.replace('/login');
        }
    }
    // 2xx的返回都会在这里处理
    console.log(response)
    return response
},(error)=>{
    // 超出2xx的返回都在错误中
    return Promise.reject(error)
})

export default service